package com.onlinelearn.userservice.service;

import com.onlinelearn.userservice.dto.RegisterRequest;
import com.onlinelearn.userservice.model.Student;
import com.onlinelearn.userservice.model.Teacher;
import com.onlinelearn.userservice.model.User;
import com.onlinelearn.userservice.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class AuthService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public User register(RegisterRequest request) {
        if (userRepository.existsByEmail(request.getEmail())) {
            throw new RuntimeException("邮箱已注册");
        }

        User user;
        switch (request.getRole()) {
            case STUDENT:
                user = new Student();
                break;
            case TEACHER:
                user = new Teacher();
                break;
            default:
                throw new RuntimeException("无效的用户角色");
        }

        user.setName(request.getName());
        user.setEmail(request.getEmail());
        user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
        user.setRole(request.getRole());

        return userRepository.save(user);
    }

    public User login(String email, String password) {
        User user = userRepository.findByEmail(email)
            .orElseThrow(() -> new RuntimeException("用户不存在"));

        if (!passwordEncoder.matches(password, user.getPasswordHash())) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }
} 